<template>
  <div class="echarts-container">
    <div class="chart-container">
      <div class="chart-title">
        <Histogram style="width: 18px; height: 18px" />
        <span>分组入组进度</span>
      </div>
      <div ref="setChartRefFZ" class="chart"></div>
    </div>
    <div class="chart-container">
      <div class="chart-title">
        <Histogram style="width: 18px; height: 18px" />
        <span>中心入组进度</span>
      </div>
      <div ref="setChartRefZX" class="chart"></div>
    </div>
  </div>
</template>
<script setup>
import { groupNumOfMonth, deptNumOfMonth } from '@/api/trial/trial';
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import * as echarts from 'echarts';
const route = useRoute();
const router = useRouter();
const crud = ref(null);
const store = useStore();
const routerQuery = ref({});
routerQuery.value = route.query;
let setChartRefFZ = ref(null);
let chartInstanceFZ = null;
let setChartRefZX = ref(null);
let chartInstanceZX = null;
const props = defineProps({
  sendTrialVal: {
    type: Object,
    default: {},
  },
});
// 初始化图表
const initChartFZ = () => {
  groupNumOfMonth(props.sendTrialVal.id).then(res => {
    const DATA = res.data.data;
    let dataName = Object.keys(DATA).filter(key => key !== 'month');
    let dataVal = Object.keys(DATA)
      .filter(key => key !== 'month')
      .map(key => DATA[key]);
    let xName = DATA.month;
    chartInstanceFZ = echarts.init(setChartRefFZ.value);
    let seriesData = [];

    dataName.forEach((item, i) => {
      seriesData.push({
        name: item,
        data: dataVal[i],
        type: 'line',
        barWidth: 20, // 设置柱子的宽度
      });
    });

    // 示例配置（可根据不同索引设置不同配置）
    let option = {
      title: {
        text: '分组入组进度',
        left: 'left',
        textStyle: {
          color: 'black',
          fontSize: 14,
        },
      },
      grid: { left: '10', right: '10', bottom: '50', top: '50', containLabel: true },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' },
      },
      legend: {
        top: '0',
        orient: 'vertical', // 设置为垂直布局
        left: 'right', // 可以放置在图表的右侧
        // top: 'middle', // 垂直居中
        textStyle: {
          color: 'black',
          fontSize: 12,
        },
        data: dataName,
      },
      xAxis: {
        type: 'category',
        data: xName, // 将你的长文本放在 data 数组中
        axisLabel: {
          interval: 0, // 强制显示所有标签
          // rotate: 30, // 如果文字很长，可以通过旋转角度来避免重叠
          formatter: function (value) {
            return value; // 你可以进一步定制格式化输出
          },
        },
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} 人', // 每个数值后加上"人"单位
        },
      },
      series: seriesData,
    };
    chartInstanceFZ.setOption(option);
  });
};
const initChartZX = () => {
  deptNumOfMonth(props.sendTrialVal.id).then(res => {
    const DATA = res.data.data;
    let dataName = Object.keys(DATA).filter(key => key !== 'month');
    let dataVal = Object.keys(DATA)
      .filter(key => key !== 'month')
      .map(key => DATA[key]);
    let xName = DATA.month;
    chartInstanceZX = echarts.init(setChartRefZX.value);
    let seriesData = [];

    dataName.forEach((item, i) => {
      seriesData.push({
        name: item,
        data: dataVal[i],
        type: 'line',
        barWidth: 20, // 设置柱子的宽度
      });
    });

    // 示例配置（可根据不同索引设置不同配置）
    let option = {
      title: {
        text: '中心入组进度',
        left: 'left',
        textStyle: {
          color: 'black',
          fontSize: 14,
        },
      },
      grid: { left: '10', right: '10', bottom: '50', top: '50', containLabel: true },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' },
      },
      legend: {
        top: '0',
        orient: 'vertical', // 设置为垂直布局
        left: 'right', // 可以放置在图表的右侧
        // top: 'middle', // 垂直居中
        textStyle: {
          color: 'black',
          fontSize: 12,
        },
        data: dataName,
      },
      xAxis: {
        type: 'category',
        data: xName, // 将你的长文本放在 data 数组中
        axisLabel: {
          interval: 0, // 强制显示所有标签
          // rotate: 30, // 如果文字很长，可以通过旋转角度来避免重叠
          formatter: function (value) {
            return value; // 你可以进一步定制格式化输出
          },
        },
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} 人', // 每个数值后加上"人"单位
        },
      },
      series: seriesData,
    };
    chartInstanceZX.setOption(option);
  });
};
const getLastTwoMonths = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1; // JS中月份是0-11，所以+1

  // 计算前两个月的年月，注意跨年情况
  const months = [];
  for (let i = 2; i >= 1; i--) {
    let m = month - i;
    let y = year;
    if (m <= 0) {
      m += 12;
      y -= 1;
    }
    months.push(`${y}年${m}月`);
  }
  return months;
};
onMounted(() => {
  nextTick(() => {
    initChartFZ();
    initChartZX();
    // 添加窗口resize监听
    window.addEventListener('resize', () => {
      chartInstanceFZ?.resize(); // 直接调用 resize
      chartInstanceZX?.resize(); // 直接调用 resize
    });
  });
});
// 组件卸载时清理
onBeforeUnmount(() => {
  if (chartInstanceFZ) {
    chartInstanceFZ.dispose(); // 清理 chartInstance
  }
  if (chartInstanceZX) {
    chartInstanceZX.dispose(); // 清理 chartInstance
  }
  window.removeEventListener('resize', () => {
    chartInstanceFZ?.resize(); // 移除事件监听
    chartInstanceZX?.resize(); // 移除事件监听
  });
});
</script>
<style scoped>
.echarts-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.chart-container {
  width: 50%;
  height: 500px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.chart-title {
  width: 100%;
  height: 30px;
  font-size: 18px;
  color: black;
  display: flex;
  align-items: center;
}
.chart {
  width: 100%;
  height: 100%;
}
</style>